#!/usr/bin/env python3

import argparse
import logging
import sys

import ghapi


def parse_arguments():
    parser = argparse.ArgumentParser()

    subparsers = parser.add_subparsers(title="commands",
                                       required=True,
                                       dest="command")

    parser_create = subparsers.add_parser('create', help="Create tag")
    parser_create.add_argument("tag")
    group = parser_create.add_mutually_exclusive_group(required=True)
    group.add_argument("--commit")
    group.add_argument("--branch")

    parser_delete = subparsers.add_parser('delete', help="Delete tag")
    parser_delete.add_argument("tag")

    for subparser in [parser_create, parser_delete]:
        subparser.add_argument("--owner", required=True, )
        subparser.add_argument("--project", required=True)
        subparser.add_argument("--oauth-token", required=True)

    return parser.parse_args()


def main():
    logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.INFO)
    args = parse_arguments()
    command = args.command
    tag = args.tag

    try:
        gh_conn = ghapi.GitHubApi(args.owner, args.project, args.oauth_token)

        if command == "create":
            if args.branch:
                commit = gh_conn.last_commit_hash_on_branch(args.branch)
            else:
                commit = args.commit
            gh_conn.create_tag_reference(tag, commit)
        if command == "delete":
            gh_conn.delete_tag_reference(tag)
    except ghapi.GitHubApiException as ex:
        logging.error(ex)
        sys.exit(1)


if __name__ == "__main__":
    main()
